package com.christina.engine.state;

import com.christina.engine.state.model.StateContext;
import com.christina.engine.state.model.StateTransitionResult;
import lombok.extern.slf4j.Slf4j;
import java.util.ArrayList;
import java.util.List;

/**
 * 抽象对话状态基类
 * 提供状态的通用实现
 * 
 * @author Christina
 */
@Slf4j
public abstract class AbstractConversationState implements ConversationState {
    
    protected final String stateName;
    protected final StateType stateType;
    protected final long timeoutMillis;
    
    protected AbstractConversationState(String stateName, StateType stateType, long timeoutMillis) {
        this.stateName = stateName;
        this.stateType = stateType;
        this.timeoutMillis = timeoutMillis;
    }
    
    protected AbstractConversationState(String stateName, StateType stateType) {
        this(stateName, stateType, -1); // 无超时
    }
    
    @Override
    public String getStateName() {
        return stateName;
    }
    
    @Override
    public StateType getStateType() {
        return stateType;
    }
    
    @Override
    public long getTimeoutMillis() {
        return timeoutMillis;
    }
    
    @Override
    public StateTransitionResult onEnter(StateContext context) {
        log.debug("Entering state: {} for session: {}", stateName, context.getSessionId());
        
        // 执行具体的进入逻辑
        StateTransitionResult result = doOnEnter(context);
        
        // 记录状态进入事件
        recordStateEvent(context, "ENTER", result);
        
        return result;
    }
    
    @Override
    public StateTransitionResult handleMessage(String message, StateContext context) {
        log.debug("Handling message in state: {} for session: {}", stateName, context.getSessionId());
        
        // 验证消息
        if (message == null || message.trim().isEmpty()) {
            return StateTransitionResult.failure("Message cannot be null or empty");
        }
        
        // 执行具体的消息处理逻辑
        StateTransitionResult result = doHandleMessage(message, context);
        
        // 记录消息处理事件
        recordStateEvent(context, "HANDLE_MESSAGE", result);
        
        return result;
    }
    
    @Override
    public StateTransitionResult onExit(StateContext context) {
        log.debug("Exiting state: {} for session: {}", stateName, context.getSessionId());
        
        // 执行具体的退出逻辑
        StateTransitionResult result = doOnExit(context);
        
        // 记录状态退出事件
        recordStateEvent(context, "EXIT", result);
        
        return result;
    }
    
    @Override
    public StateTransitionResult onTimeout(StateContext context) {
        log.warn("State timeout in: {} for session: {}", stateName, context.getSessionId());
        
        // 执行具体的超时处理逻辑
        StateTransitionResult result = doOnTimeout(context);
        
        // 记录超时事件
        recordStateEvent(context, "TIMEOUT", result);
        
        return result;
    }
    
    @Override
    public boolean canTransitionTo(ConversationState targetState, StateContext context) {
        if (targetState == null) {
            return false;
        }
        
        // 检查是否在允许的下一个状态列表中
        List<ConversationState> possibleStates = getPossibleNextStates(context);
        return possibleStates.stream()
                .anyMatch(state -> state.getStateName().equals(targetState.getStateName()));
    }
    
    @Override
    public List<ConversationState> getPossibleNextStates(StateContext context) {
        // 默认实现返回空列表，子类应该重写此方法
        return new ArrayList<>();
    }
    
    @Override
    public boolean isCompleted(StateContext context) {
        // 默认实现，子类可以重写
        return stateType == StateType.COMPLETED || stateType == StateType.TERMINATED;
    }
    
    /**
     * 具体的进入状态逻辑，子类必须实现
     * 
     * @param context 状态上下文
     * @return 转换结果
     */
    protected abstract StateTransitionResult doOnEnter(StateContext context);
    
    /**
     * 具体的消息处理逻辑，子类必须实现
     * 
     * @param message 消息内容
     * @param context 状态上下文
     * @return 转换结果
     */
    protected abstract StateTransitionResult doHandleMessage(String message, StateContext context);
    
    /**
     * 具体的退出状态逻辑，子类可以重写
     * 
     * @param context 状态上下文
     * @return 转换结果
     */
    protected StateTransitionResult doOnExit(StateContext context) {
        // 默认实现，清理状态数据
        context.clearStateData();
        return StateTransitionResult.success(null, "Exited state: " + stateName);
    }
    
    /**
     * 具体的超时处理逻辑，子类可以重写
     * 
     * @param context 状态上下文
     * @return 转换结果
     */
    protected StateTransitionResult doOnTimeout(StateContext context) {
        // 默认超时处理：结束对话
        return StateTransitionResult.endConversation("State timeout in: " + stateName);
    }
    
    /**
     * 验证用户输入
     * 
     * @param input 用户输入
     * @param context 状态上下文
     * @return 验证结果
     */
    protected ValidationResult validateInput(String input, StateContext context) {
        if (input == null || input.trim().isEmpty()) {
            return ValidationResult.invalid("输入不能为空");
        }
        
        if (input.length() > 1000) {
            return ValidationResult.invalid("输入内容过长，请控制在1000字符以内");
        }
        
        return ValidationResult.valid();
    }
    
    /**
     * 检查是否为取消命令
     * 
     * @param input 用户输入
     * @return 是否为取消命令
     */
    protected boolean isCancelCommand(String input) {
        if (input == null) {
            return false;
        }
        
        String lowerInput = input.toLowerCase().trim();
        return lowerInput.equals("取消") || 
               lowerInput.equals("cancel") || 
               lowerInput.equals("退出") || 
               lowerInput.equals("exit") ||
               lowerInput.equals("quit");
    }
    
    /**
     * 检查是否为帮助命令
     * 
     * @param input 用户输入
     * @return 是否为帮助命令
     */
    protected boolean isHelpCommand(String input) {
        if (input == null) {
            return false;
        }
        
        String lowerInput = input.toLowerCase().trim();
        return lowerInput.equals("帮助") || 
               lowerInput.equals("help") || 
               lowerInput.equals("?") ||
               lowerInput.equals("？");
    }
    
    /**
     * 获取帮助信息
     * 
     * @param context 状态上下文
     * @return 帮助信息
     */
    protected String getHelpMessage(StateContext context) {
        return "当前状态：" + stateName + "\n" +
               "您可以输入 '取消' 或 'cancel' 来退出当前操作\n" +
               "输入 '帮助' 或 'help' 来获取帮助信息";
    }
    
    /**
     * 记录状态事件
     * 
     * @param context 状态上下文
     * @param eventType 事件类型
     * @param result 转换结果
     */
    protected void recordStateEvent(StateContext context, String eventType, StateTransitionResult result) {
        if (context.getDebugMode()) {
            log.debug("State event - Session: {}, State: {}, Event: {}, Success: {}", 
                    context.getSessionId(), stateName, eventType, 
                    result != null ? result.isSuccessful() : "null");
        }
        
        // 可以在这里添加更详细的事件记录逻辑
        context.setAttribute("lastEvent", eventType);
        context.setAttribute("lastEventTime", java.time.LocalDateTime.now());
    }
    
    /**
     * 输入验证结果
     */
    protected static class ValidationResult {
        private final boolean valid;
        private final String errorMessage;
        
        private ValidationResult(boolean valid, String errorMessage) {
            this.valid = valid;
            this.errorMessage = errorMessage;
        }
        
        public static ValidationResult valid() {
            return new ValidationResult(true, null);
        }
        
        public static ValidationResult invalid(String errorMessage) {
            return new ValidationResult(false, errorMessage);
        }
        
        public boolean isValid() {
            return valid;
        }
        
        public String getErrorMessage() {
            return errorMessage;
        }
    }
    
    @Override
    public String toString() {
        return String.format("ConversationState{name='%s', type=%s, timeout=%d}", 
                stateName, stateType, timeoutMillis);
    }
}